package cn.lanqiao.blog.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.lanqiao.blog.dao.ArticleMapper;
import cn.lanqiao.blog.dao.CommentMapper;
import cn.lanqiao.blog.vo.CommentVO;
import cn.lanqiao.blog.service.CommentService;

@Service
public class CommentServiceImpl implements CommentService{

	@Autowired
	private CommentMapper commentMapper;
	
	@Autowired
	private ArticleMapper articleMapper;
	
	//存放父评论即其所有子评论
    private List<CommentVO> tempReplys = new ArrayList<>();

	@Override
	public List<CommentVO> getCommentList(Integer articleId) {
		
		//获得所有父评论
		List<CommentVO> parentComments = commentMapper.getCommentsByToCommentIdNull(articleId);
		
		for(CommentVO parentComment : parentComments) {
			//根据父评论id获取子评论
			List<CommentVO> childComments = commentMapper.getCommentsByToCommentIdNotNull(articleId, parentComment.getId());
			combineChildren(articleId, childComments);
			parentComment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return parentComments;
	}
	//获取一级子评论
	public void combineChildren(Integer articleId, List<CommentVO> childComments) {
//      判断是否有一级子评论
      if(childComments.size() > 0){
//        循环找出子评论的id
          for(CommentVO childComment : childComments){
              tempReplys.add(childComment);
              Integer childId = childComment.getId();
//                  查询出子二级评论
              recursively(articleId, childId);
          }
      }
  }
	//递归获取二级子评论
	private void recursively(Integer articleId, Integer childId) {
      List<CommentVO> replayComments = commentMapper.getCommentsByToCommentIdNotNull(articleId, childId);
      if(replayComments.size() > 0){
          for(CommentVO replayComment : replayComments){        	  
              Integer replayId = replayComment.getId();
              tempReplys.add(replayComment);
              recursively(articleId,replayId);
          }
      }
  }
	//新增评论
	@Override
	public int saveComment(CommentVO comment) {
		int commentable = articleMapper.getCommentable(comment.getArticleId());
		//所有人可评论
		if(commentable == 0) {
			comment.setTime(new Date());	
			//查询当前评论数
			commentMapper.getCommentCountById(comment.getArticleId());
			articleMapper.increaseCommentCount(comment.getArticleId());
			return commentMapper.insert(comment);
			
		}else if (commentable == 1) {
			//仅粉丝可评论
			Integer r = articleMapper.getFansCommentable(comment.getCommentUserId(), comment.getArticleId());
			if(r != null) {
				comment.setTime(new Date());				
				//查询当前评论数
				commentMapper.getCommentCountById(comment.getArticleId());
				articleMapper.increaseCommentCount(comment.getArticleId());
				return commentMapper.insert(comment);
			}else {
				return 0; 
			}
		}
		return 0 ;
	}


	
	
}
